﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;

namespace Mymap
{
    public partial class ChartRendererDialog : Form
    {
        #region 控件声明
        private TableLayoutPanel tableLayoutPanel1;
        private Label lblTitle;
        private GroupBox groupBoxFields;
        private ListBox listBoxAvailableFields;
        private ListBox listBoxSelectedFields;
        private Button buttonAdd;
        private Button buttonAddAll;
        private Button buttonRemove;
        private Button buttonRemoveAll;
        private GroupBox groupBoxColorSettings;
        private ComboBox comboBoxFieldForColor;
        private Button buttonSetFieldColor;
        private Panel panelColorPreview;
        private GroupBox groupBoxSettings;
        private NumericUpDown numericUpDownWidth;
        private NumericUpDown numericUpDownHeight;
        private Button buttonBaseColor;
        private Panel panelButtons;
        private Button buttonOK;
        private Button buttonCancel;
        private ColorDialog colorDialog;
        private ToolTip toolTip;
        #endregion

        #region 成员变量
        private IFeatureLayer m_featureLayer;
        private Dictionary<string, Color> m_fieldColors = new Dictionary<string, Color>();
        private List<string> m_availableFields = new List<string>();
        private List<string> m_selectedFields = new List<string>();
        private Color m_baseColor = Color.Blue;
        private System.ComponentModel.IContainer components = null;
        #endregion

        #region 构造函数
        public ChartRendererDialog(IFeatureLayer featureLayer)
        {
            InitializeComponent();
            m_featureLayer = featureLayer;
            LoadNumericFields();
            WireEvents();
        }
        #endregion

        #region 初始化方法
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.lblTitle = new System.Windows.Forms.Label();
            this.groupBoxFields = new System.Windows.Forms.GroupBox();
            this.listBoxAvailableFields = new System.Windows.Forms.ListBox();
            this.listBoxSelectedFields = new System.Windows.Forms.ListBox();
            this.buttonAdd = new System.Windows.Forms.Button();
            this.buttonAddAll = new System.Windows.Forms.Button();
            this.buttonRemove = new System.Windows.Forms.Button();
            this.buttonRemoveAll = new System.Windows.Forms.Button();
            this.groupBoxColorSettings = new System.Windows.Forms.GroupBox();
            this.comboBoxFieldForColor = new System.Windows.Forms.ComboBox();
            this.buttonSetFieldColor = new System.Windows.Forms.Button();
            this.panelColorPreview = new System.Windows.Forms.Panel();
            this.groupBoxSettings = new System.Windows.Forms.GroupBox();
            this.numericUpDownWidth = new System.Windows.Forms.NumericUpDown();
            this.numericUpDownHeight = new System.Windows.Forms.NumericUpDown();
            this.buttonBaseColor = new System.Windows.Forms.Button();
            this.panelButtons = new System.Windows.Forms.Panel();
            this.buttonOK = new System.Windows.Forms.Button();
            this.buttonCancel = new System.Windows.Forms.Button();
            this.colorDialog = new System.Windows.Forms.ColorDialog();
            this.toolTip = new System.Windows.Forms.ToolTip(this.components);

            SuspendLayout();

            // 窗体设置
            this.Text = "柱状统计专题地图设置";
            this.Size = new System.Drawing.Size(600, 600);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 主 TableLayoutPanel
            this.tableLayoutPanel1.Dock = DockStyle.Fill;
            this.tableLayoutPanel1.ColumnCount = 1;
            this.tableLayoutPanel1.RowCount = 5;
            this.tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
            this.tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 50F));
            this.tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
            this.tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
            this.tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
            this.tableLayoutPanel1.Padding = new Padding(5);

            // 标题
            this.lblTitle.Text = "柱状统计专题地图设置";
            this.lblTitle.Font = new Font("微软雅黑", 12F, FontStyle.Bold);
            this.lblTitle.TextAlign = ContentAlignment.MiddleCenter;
            this.lblTitle.Dock = DockStyle.Fill;
            this.lblTitle.Margin = new Padding(10, 15, 10, 10);
            this.tableLayoutPanel1.Controls.Add(this.lblTitle, 0, 0);

            // 字段选择区域
            InitializeFieldsGroupBox();
            this.tableLayoutPanel1.Controls.Add(this.groupBoxFields, 0, 1);

            // 字段颜色设置区域
            InitializeColorSettingsGroupBox();
            this.tableLayoutPanel1.Controls.Add(this.groupBoxColorSettings, 0, 2);

            // 柱状图参数设置区域
            InitializeSettingsGroupBox();
            this.tableLayoutPanel1.Controls.Add(this.groupBoxSettings, 0, 3);

            // 按钮区域
            InitializeButtonsPanel();
            this.tableLayoutPanel1.Controls.Add(this.panelButtons, 0, 4);

            this.Controls.Add(this.tableLayoutPanel1);
            ResumeLayout(false);
        }

        private void InitializeFieldsGroupBox()
        {
            this.groupBoxFields = new GroupBox();
            this.groupBoxFields.Text = "字段选择（数值型字段）";
            this.groupBoxFields.Dock = DockStyle.Fill;
            this.groupBoxFields.Margin = new Padding(10);
            this.groupBoxFields.Font = new Font("微软雅黑", 9F, FontStyle.Regular);

            // 内部 TableLayoutPanel - 3列布局
            TableLayoutPanel fieldsLayout = new TableLayoutPanel();
            fieldsLayout.Dock = DockStyle.Fill;
            fieldsLayout.ColumnCount = 3;
            fieldsLayout.RowCount = 2;
            fieldsLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 45F));
            fieldsLayout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            fieldsLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 45F));
            fieldsLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
            fieldsLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));

            // 左侧可用字段标签
            Label lblAvailable = new Label();
            lblAvailable.Text = "可用字段:";
            lblAvailable.Dock = DockStyle.Bottom;
            lblAvailable.TextAlign = ContentAlignment.MiddleLeft;
            lblAvailable.Margin = new Padding(5, 0, 5, 2);
            fieldsLayout.Controls.Add(lblAvailable, 0, 0);

            // 左侧可用字段列表框
            this.listBoxAvailableFields = new ListBox();
            this.listBoxAvailableFields.Dock = DockStyle.Fill;
            this.listBoxAvailableFields.Margin = new Padding(5);
            this.listBoxAvailableFields.BorderStyle = BorderStyle.FixedSingle;
            this.listBoxAvailableFields.Font = new Font("微软雅黑", 9F);
            this.listBoxAvailableFields.SelectionMode = SelectionMode.MultiExtended;
            fieldsLayout.Controls.Add(this.listBoxAvailableFields, 0, 1);

            // 中间操作按钮面板
            Panel buttonPanel = new Panel();
            buttonPanel.Dock = DockStyle.Fill;
            buttonPanel.Margin = new Padding(5);

            TableLayoutPanel buttonLayout = new TableLayoutPanel();
            buttonLayout.Dock = DockStyle.Fill;
            buttonLayout.RowCount = 4;
            buttonLayout.ColumnCount = 1;
            buttonLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
            buttonLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
            buttonLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
            buttonLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));

            // 向右添加按钮
            this.buttonAdd = new Button();
            this.buttonAdd.Text = ">";
            this.buttonAdd.Size = new Size(40, 30);
            this.buttonAdd.Margin = new Padding(0, 20, 0, 5);
            this.buttonAdd.Font = new Font("微软雅黑", 10F, FontStyle.Bold);
            buttonLayout.Controls.Add(this.buttonAdd, 0, 0);

            // 向右全部添加按钮
            this.buttonAddAll = new Button();
            this.buttonAddAll.Text = ">>";
            this.buttonAddAll.Size = new Size(40, 30);
            this.buttonAddAll.Margin = new Padding(0, 5, 0, 5);
            this.buttonAddAll.Font = new Font("微软雅黑", 10F, FontStyle.Bold);
            buttonLayout.Controls.Add(this.buttonAddAll, 0, 1);

            // 向左移除按钮
            this.buttonRemove = new Button();
            this.buttonRemove.Text = "<";
            this.buttonRemove.Size = new Size(40, 30);
            this.buttonRemove.Margin = new Padding(0, 5, 0, 5);
            this.buttonRemove.Font = new Font("微软雅黑", 10F, FontStyle.Bold);
            buttonLayout.Controls.Add(this.buttonRemove, 0, 2);

            // 向左全部移除按钮
            this.buttonRemoveAll = new Button();
            this.buttonRemoveAll.Text = "<<";
            this.buttonRemoveAll.Size = new Size(40, 30);
            this.buttonRemoveAll.Margin = new Padding(0, 5, 0, 20);
            this.buttonRemoveAll.Font = new Font("微软雅黑", 10F, FontStyle.Bold);
            buttonLayout.Controls.Add(this.buttonRemoveAll, 0, 3);

            buttonPanel.Controls.Add(buttonLayout);
            fieldsLayout.Controls.Add(buttonPanel, 1, 0);
            fieldsLayout.SetRowSpan(buttonPanel, 2);

            // 右侧已选择字段标签
            Label lblSelected = new Label();
            lblSelected.Text = "已选择字段:";
            lblSelected.Dock = DockStyle.Bottom;
            lblSelected.TextAlign = ContentAlignment.MiddleLeft;
            lblSelected.Margin = new Padding(5, 0, 5, 2);
            fieldsLayout.Controls.Add(lblSelected, 2, 0);

            // 右侧已选择字段列表框
            this.listBoxSelectedFields = new ListBox();
            this.listBoxSelectedFields.Dock = DockStyle.Fill;
            this.listBoxSelectedFields.Margin = new Padding(5);
            this.listBoxSelectedFields.BorderStyle = BorderStyle.FixedSingle;
            this.listBoxSelectedFields.Font = new Font("微软雅黑", 9F);
            this.listBoxSelectedFields.SelectionMode = SelectionMode.One;
            fieldsLayout.Controls.Add(this.listBoxSelectedFields, 2, 1);

            this.groupBoxFields.Controls.Add(fieldsLayout);
        }

        private void InitializeColorSettingsGroupBox()
        {
            this.groupBoxColorSettings = new GroupBox();
            this.groupBoxColorSettings.Text = "字段颜色设置";
            this.groupBoxColorSettings.Dock = DockStyle.Fill;
            this.groupBoxColorSettings.Margin = new Padding(10, 5, 10, 5);
            this.groupBoxColorSettings.Font = new Font("微软雅黑", 9F, FontStyle.Regular);

            // 内部 TableLayoutPanel
            TableLayoutPanel colorLayout = new TableLayoutPanel();
            colorLayout.Dock = DockStyle.Fill;
            colorLayout.ColumnCount = 4;
            colorLayout.RowCount = 1;
            colorLayout.Padding = new Padding(10);
            colorLayout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            colorLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40F));
            colorLayout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            colorLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20F));

            // 字段选择标签
            Label lblFieldForColor = new Label();
            lblFieldForColor.Text = "选择字段:";
            lblFieldForColor.TextAlign = ContentAlignment.MiddleLeft;
            lblFieldForColor.Dock = DockStyle.Fill;
            lblFieldForColor.Margin = new Padding(0, 0, 5, 0);
            colorLayout.Controls.Add(lblFieldForColor, 0, 0);

            // 字段下拉框
            this.comboBoxFieldForColor = new ComboBox();
            this.comboBoxFieldForColor.Dock = DockStyle.Fill;
            this.comboBoxFieldForColor.Margin = new Padding(0, 0, 5, 0);
            this.comboBoxFieldForColor.DropDownStyle = ComboBoxStyle.DropDownList;
            this.comboBoxFieldForColor.Font = new Font("微软雅黑", 9F);
            this.comboBoxFieldForColor.Enabled = false;
            colorLayout.Controls.Add(this.comboBoxFieldForColor, 1, 0);

            // 设置颜色按钮
            this.buttonSetFieldColor = new Button();
            this.buttonSetFieldColor.Text = "设置颜色";
            this.buttonSetFieldColor.Dock = DockStyle.Fill;
            this.buttonSetFieldColor.Margin = new Padding(0, 0, 5, 0);
            this.buttonSetFieldColor.Font = new Font("微软雅黑", 9F);
            this.buttonSetFieldColor.Enabled = false;
            colorLayout.Controls.Add(this.buttonSetFieldColor, 2, 0);

            // 颜色预览面板
            this.panelColorPreview = new Panel();
            this.panelColorPreview.Dock = DockStyle.Fill;
            this.panelColorPreview.Margin = new Padding(0);
            this.panelColorPreview.BorderStyle = BorderStyle.FixedSingle;
            this.panelColorPreview.BackColor = Color.Gray;
            colorLayout.Controls.Add(this.panelColorPreview, 3, 0);

            this.groupBoxColorSettings.Controls.Add(colorLayout);
        }

        private void InitializeSettingsGroupBox()
        {
            this.groupBoxSettings = new GroupBox();
            this.groupBoxSettings.Text = "柱状图参数设置";
            this.groupBoxSettings.Dock = DockStyle.Fill;
            this.groupBoxSettings.Margin = new Padding(10, 5, 10, 10);
            this.groupBoxSettings.Font = new Font("微软雅黑", 9F, FontStyle.Regular);

            // 内部 TableLayoutPanel
            TableLayoutPanel settingsLayout = new TableLayoutPanel();
            settingsLayout.Dock = DockStyle.Fill;
            settingsLayout.ColumnCount = 6;
            settingsLayout.RowCount = 2;
            settingsLayout.Padding = new Padding(10);

            settingsLayout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            settingsLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 15F));
            settingsLayout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            settingsLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 15F));
            settingsLayout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            settingsLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40F));

            // 宽度设置
            Label lblWidth = new Label();
            lblWidth.Text = "宽度:";
            lblWidth.TextAlign = ContentAlignment.MiddleLeft;
            lblWidth.Dock = DockStyle.Fill;
            lblWidth.Margin = new Padding(0, 5, 5, 5);
            settingsLayout.Controls.Add(lblWidth, 0, 0);

            this.numericUpDownWidth = new NumericUpDown();
            this.numericUpDownWidth.Dock = DockStyle.Fill;
            this.numericUpDownWidth.Margin = new Padding(0, 5, 5, 5);
            this.numericUpDownWidth.Minimum = 10;
            this.numericUpDownWidth.Maximum = 200;
            this.numericUpDownWidth.Value = 50;
            settingsLayout.Controls.Add(this.numericUpDownWidth, 1, 0);

            Label lblWidthUnit = new Label();
            lblWidthUnit.Text = "像素";
            lblWidthUnit.TextAlign = ContentAlignment.MiddleLeft;
            lblWidthUnit.Dock = DockStyle.Fill;
            lblWidthUnit.Margin = new Padding(0, 5, 15, 5);
            settingsLayout.Controls.Add(lblWidthUnit, 2, 0);

            // 高度设置
            Label lblHeight = new Label();
            lblHeight.Text = "高度:";
            lblHeight.TextAlign = ContentAlignment.MiddleLeft;
            lblHeight.Dock = DockStyle.Fill;
            lblHeight.Margin = new Padding(0, 5, 5, 5);
            settingsLayout.Controls.Add(lblHeight, 3, 0);

            this.numericUpDownHeight = new NumericUpDown();
            this.numericUpDownHeight.Dock = DockStyle.Fill;
            this.numericUpDownHeight.Margin = new Padding(0, 5, 5, 5);
            this.numericUpDownHeight.Minimum = 10;
            this.numericUpDownHeight.Maximum = 500;
            this.numericUpDownHeight.Value = 100;
            settingsLayout.Controls.Add(this.numericUpDownHeight, 4, 0);

            Label lblHeightUnit = new Label();
            lblHeightUnit.Text = "像素";
            lblHeightUnit.TextAlign = ContentAlignment.MiddleLeft;
            lblHeightUnit.Dock = DockStyle.Fill;
            lblHeightUnit.Margin = new Padding(0, 5, 0, 5);
            settingsLayout.Controls.Add(lblHeightUnit, 5, 0);

            // 基础颜色设置（第二行，跨所有列）
            Label lblBaseColor = new Label();
            lblBaseColor.Text = "基础颜色:";
            lblBaseColor.TextAlign = ContentAlignment.MiddleLeft;
            lblBaseColor.Dock = DockStyle.Fill;
            lblBaseColor.Margin = new Padding(0, 10, 5, 5);
            settingsLayout.Controls.Add(lblBaseColor, 0, 1);

            this.buttonBaseColor = new Button();
            this.buttonBaseColor.Text = "选择基础颜色";
            this.buttonBaseColor.Dock = DockStyle.Fill;
            this.buttonBaseColor.Margin = new Padding(0, 10, 5, 5);
            this.buttonBaseColor.BackColor = Color.Blue;
            this.buttonBaseColor.ForeColor = Color.White;
            this.buttonBaseColor.FlatStyle = FlatStyle.Flat;
            this.buttonBaseColor.TextAlign = ContentAlignment.MiddleLeft;
            settingsLayout.SetColumnSpan(this.buttonBaseColor, 5);
            settingsLayout.Controls.Add(this.buttonBaseColor, 1, 1);

            this.groupBoxSettings.Controls.Add(settingsLayout);
        }

        private void InitializeButtonsPanel()
        {
            this.panelButtons = new Panel();
            this.panelButtons.Dock = DockStyle.Fill;
            this.panelButtons.Margin = new Padding(10, 5, 10, 15);
            this.panelButtons.Height = 40;

            FlowLayoutPanel flowLayoutButtons = new FlowLayoutPanel();
            flowLayoutButtons.Dock = DockStyle.Fill;
            flowLayoutButtons.FlowDirection = FlowDirection.RightToLeft;
            flowLayoutButtons.Padding = new Padding(0, 5, 0, 5);

            this.buttonCancel = new Button();
            this.buttonCancel.Text = "取消";
            this.buttonCancel.Size = new Size(80, 30);
            this.buttonCancel.Margin = new Padding(5, 0, 0, 0);
            this.buttonCancel.Font = new Font("微软雅黑", 9F);
            this.buttonCancel.DialogResult = DialogResult.Cancel;

            this.buttonOK = new Button();
            this.buttonOK.Text = "确定";
            this.buttonOK.Size = new Size(80, 30);
            this.buttonOK.Margin = new Padding(5, 0, 0, 0);
            this.buttonOK.Font = new Font("微软雅黑", 9F, FontStyle.Bold);
            this.buttonOK.BackColor = Color.SteelBlue;
            this.buttonOK.ForeColor = Color.White;
            this.buttonOK.FlatStyle = FlatStyle.Flat;

            flowLayoutButtons.Controls.Add(this.buttonCancel);
            flowLayoutButtons.Controls.Add(this.buttonOK);
            this.panelButtons.Controls.Add(flowLayoutButtons);
        }

        private void WireEvents()
        {
            // 字段操作按钮事件
            this.buttonAdd.Click += ButtonAdd_Click;
            this.buttonAddAll.Click += ButtonAddAll_Click;
            this.buttonRemove.Click += ButtonRemove_Click;
            this.buttonRemoveAll.Click += ButtonRemoveAll_Click;

            // 颜色设置事件
            this.buttonSetFieldColor.Click += ButtonSetFieldColor_Click;
            this.buttonBaseColor.Click += ButtonBaseColor_Click;
            this.comboBoxFieldForColor.SelectedIndexChanged += ComboBoxFieldForColor_SelectedIndexChanged;

            // 列表选择事件
            this.listBoxSelectedFields.SelectedIndexChanged += ListBoxSelectedFields_SelectedIndexChanged;

            // 确定取消按钮事件
            this.buttonOK.Click += ButtonOK_Click;
            this.buttonCancel.Click += ButtonCancel_Click;

            // 设置工具提示
            this.toolTip.SetToolTip(this.buttonAdd, "添加选中的字段到已选择列表");
            this.toolTip.SetToolTip(this.buttonAddAll, "添加所有字段到已选择列表");
            this.toolTip.SetToolTip(this.buttonRemove, "从已选择列表中移除选中的字段");
            this.toolTip.SetToolTip(this.buttonRemoveAll, "移除所有已选择的字段");
            this.toolTip.SetToolTip(this.buttonSetFieldColor, "为选中的字段设置颜色");
            this.toolTip.SetToolTip(this.buttonBaseColor, "设置基础颜色，系统将基于此颜色自动生成其他字段的颜色");
        }
        #endregion

        #region 字段操作方法
        private void LoadNumericFields()
        {
            if (m_featureLayer == null) return;

            IFeatureClass featureClass = m_featureLayer.FeatureClass;
            if (featureClass == null) return;

            this.listBoxAvailableFields.Items.Clear();
            m_availableFields.Clear();

            for (int i = 0; i < featureClass.Fields.FieldCount; i++)
            {
                IField field = featureClass.Fields.get_Field(i);

                // 只添加数值型字段
                if (field.Type == esriFieldType.esriFieldTypeDouble ||
                    field.Type == esriFieldType.esriFieldTypeInteger ||
                    field.Type == esriFieldType.esriFieldTypeSingle ||
                    field.Type == esriFieldType.esriFieldTypeSmallInteger)
                {
                    m_availableFields.Add(field.Name);
                    this.listBoxAvailableFields.Items.Add(field.Name);
                }
            }
        }

        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            if (this.listBoxAvailableFields.SelectedItems.Count == 0) return;

            // 创建临时列表来存储选中的项
            List<object> selectedItems = new List<object>();
            foreach (var item in this.listBoxAvailableFields.SelectedItems)
            {
                selectedItems.Add(item);
            }

            // 处理每个选中的字段
            foreach (var item in selectedItems)
            {
                string fieldName = item.ToString();
                if (!m_selectedFields.Contains(fieldName))
                {
                    m_selectedFields.Add(fieldName);
                    this.listBoxSelectedFields.Items.Add(fieldName);
                    this.comboBoxFieldForColor.Items.Add(fieldName);

                    // 为字段设置默认颜色
                    if (!m_fieldColors.ContainsKey(fieldName))
                    {
                        m_fieldColors[fieldName] = GenerateColor(m_selectedFields.Count - 1);
                    }
                }
            }

            // 从可用列表中移除（使用临时列表）
            foreach (var item in selectedItems)
            {
                this.listBoxAvailableFields.Items.Remove(item);
            }

            UpdateColorControls();
        }

        private void ButtonAddAll_Click(object sender, EventArgs e)
        {
            if (this.listBoxAvailableFields.Items.Count == 0) return;

            // 创建临时列表
            var allFieldNames = this.listBoxAvailableFields.Items
                .Cast<object>()
                .Select(item => item.ToString())
                .ToList();

            foreach (string fieldName in allFieldNames)
            {
                if (!m_selectedFields.Contains(fieldName))
                {
                    m_selectedFields.Add(fieldName);
                    this.listBoxSelectedFields.Items.Add(fieldName);
                    this.comboBoxFieldForColor.Items.Add(fieldName);

                    // 为字段设置默认颜色
                    if (!m_fieldColors.ContainsKey(fieldName))
                    {
                        m_fieldColors[fieldName] = GenerateColor(m_selectedFields.Count - 1);
                    }
                }
            }

            this.listBoxAvailableFields.Items.Clear();
            UpdateColorControls();
        }

        private void ButtonRemove_Click(object sender, EventArgs e)
        {
            if (this.listBoxSelectedFields.SelectedItem == null) return;

            string fieldName = this.listBoxSelectedFields.SelectedItem.ToString();
            RemoveField(fieldName);
        }

        private void ButtonRemoveAll_Click(object sender, EventArgs e)
        {
            // 创建临时列表
            var selectedFieldNames = this.listBoxSelectedFields.Items
                .Cast<object>()
                .Select(item => item.ToString())
                .ToList();

            foreach (string fieldName in selectedFieldNames)
            {
                this.listBoxAvailableFields.Items.Add(fieldName);
            }

            m_selectedFields.Clear();
            this.listBoxSelectedFields.Items.Clear();
            this.comboBoxFieldForColor.Items.Clear();
            m_fieldColors.Clear();

            UpdateColorControls();
        }

        private void RemoveField(string fieldName)
        {
            m_selectedFields.Remove(fieldName);
            this.listBoxSelectedFields.Items.Remove(fieldName);
            this.comboBoxFieldForColor.Items.Remove(fieldName);
            this.listBoxAvailableFields.Items.Add(fieldName);

            // 移除颜色设置
            if (m_fieldColors.ContainsKey(fieldName))
            {
                m_fieldColors.Remove(fieldName);
            }

            UpdateColorControls();
        }
        #endregion

        #region 颜色操作方法
        private Color GenerateColor(int index)
        {
            // 基于基础颜色生成变化
            Random rand = new Random(index);
            int r = Math.Max(0, Math.Min(255, m_baseColor.R + rand.Next(-30, 30)));
            int g = Math.Max(0, Math.Min(255, m_baseColor.G + rand.Next(-30, 30)));
            int b = Math.Max(0, Math.Min(255, m_baseColor.B + rand.Next(-30, 30)));
            return Color.FromArgb(r, g, b);
        }

        private void UpdateColorControls()
        {
            // 更新颜色下拉框状态
            this.comboBoxFieldForColor.Enabled = (this.comboBoxFieldForColor.Items.Count > 0);
            this.buttonSetFieldColor.Enabled = (this.comboBoxFieldForColor.Items.Count > 0);

            // 如果有字段，选择第一个
            if (this.comboBoxFieldForColor.Items.Count > 0 && this.comboBoxFieldForColor.SelectedIndex == -1)
            {
                this.comboBoxFieldForColor.SelectedIndex = 0;
            }

            // 更新颜色预览
            UpdateColorPreview();
        }

        private void UpdateColorPreview()
        {
            if (this.comboBoxFieldForColor.SelectedItem != null)
            {
                string fieldName = this.comboBoxFieldForColor.SelectedItem.ToString();
                if (m_fieldColors.ContainsKey(fieldName))
                {
                    this.panelColorPreview.BackColor = m_fieldColors[fieldName];
                }
                else
                {
                    this.panelColorPreview.BackColor = Color.Gray;
                }
            }
            else
            {
                this.panelColorPreview.BackColor = Color.Gray;
            }
        }

        private void ButtonSetFieldColor_Click(object sender, EventArgs e)
        {
            if (this.comboBoxFieldForColor.SelectedItem == null) return;

            string fieldName = this.comboBoxFieldForColor.SelectedItem.ToString();

            this.colorDialog.Color = m_fieldColors.ContainsKey(fieldName) ?
                m_fieldColors[fieldName] : m_baseColor;

            if (this.colorDialog.ShowDialog() == DialogResult.OK)
            {
                m_fieldColors[fieldName] = this.colorDialog.Color;
                UpdateColorPreview();
            }
        }

        private void ButtonBaseColor_Click(object sender, EventArgs e)
        {
            this.colorDialog.Color = m_baseColor;

            if (this.colorDialog.ShowDialog() == DialogResult.OK)
            {
                m_baseColor = this.colorDialog.Color;
                this.buttonBaseColor.BackColor = m_baseColor;
                this.buttonBaseColor.ForeColor = GetContrastColor(m_baseColor);

                // 重新生成所有字段颜色
                RegenerateFieldColors();
                UpdateColorPreview();
            }
        }

        private void RegenerateFieldColors()
        {
            for (int i = 0; i < m_selectedFields.Count; i++)
            {
                string fieldName = m_selectedFields[i];
                m_fieldColors[fieldName] = GenerateColor(i);
            }
        }
        #endregion

        #region 事件处理方法
        private void ComboBoxFieldForColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateColorPreview();

            // 同步列表选择
            if (this.comboBoxFieldForColor.SelectedItem != null)
            {
                string fieldName = this.comboBoxFieldForColor.SelectedItem.ToString();
                int index = this.listBoxSelectedFields.Items.IndexOf(fieldName);
                if (index >= 0)
                {
                    this.listBoxSelectedFields.SelectedIndex = index;
                }
            }
        }

        private void ListBoxSelectedFields_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 同步下拉框选择
            if (this.listBoxSelectedFields.SelectedItem != null)
            {
                string fieldName = this.listBoxSelectedFields.SelectedItem.ToString();
                int index = this.comboBoxFieldForColor.Items.IndexOf(fieldName);
                if (index >= 0)
                {
                    this.comboBoxFieldForColor.SelectedIndex = index;
                }
            }
        }

        private void ButtonOK_Click(object sender, EventArgs e)
        {
            if (m_selectedFields.Count == 0)
            {
                MessageBox.Show("请至少选择一个字段！", "提示",
                               MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void ButtonCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
        #endregion

        #region 辅助方法
        private Color GetContrastColor(Color color)
        {
            double luminance = (0.299 * color.R + 0.587 * color.G + 0.114 * color.B) / 255;
            return luminance > 0.5 ? Color.Black : Color.White;
        }
        #endregion

        #region 公共属性
        public List<string> GetSelectedFields()
        {
            return new List<string>(m_selectedFields);
        }

        public Dictionary<string, Color> GetFieldColors()
        {
            return new Dictionary<string, Color>(m_fieldColors);
        }

        public double ChartWidth
        {
            get { return (double)this.numericUpDownWidth.Value; }
        }

        public double ChartHeight
        {
            get { return (double)this.numericUpDownHeight.Value; }
        }

        public Color BaseColor
        {
            get { return m_baseColor; }
        }
        #endregion

        #region 清理资源
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        #endregion
    }
}